﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Printing;
using System.Windows.Media.Imaging;
using PrintToPDF.Helpers;
using PrintToPDF;

namespace StrategyMap
{
    public partial class Map : UserControl
    {
        // create an instance of PrintDocument
        public void Print_Map()
        {
            PrintDocument document = new PrintDocument();

            // tell the API what to print

            document.PrintPage += (s, args) =>
                {
                    args.PageVisual = this.LayoutRoot;
                };

            // call the Print() with a proper name which will be visible in the Print Queue

            document.Print("Strategy Map - " + DateTime.Now.ToString());
        }

        private Byte[] printBuffer;
        private System.Threading.SynchronizationContext printSyncContext;
        private System.IO.Stream printStream;

        public void CreateFile()
        {          
          SaveFileDialog fsd = new SaveFileDialog();
          fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

          if(fsd.ShowDialog() == true)
          {

            //Create WriteableBitmap object which is what is being exported.
            WriteableBitmap wBitmap = new WriteableBitmap(LayoutRoot, null);
            int hgt = wBitmap.PixelHeight;
            int wdth = wBitmap.PixelWidth;

            //Create EditableImage oblect and iterrate through WriteableBitmap pixels to set EditableImage pixels
            EditableImage ei = new EditableImage(wdth, hgt);

            for (int y = 0; y < hgt; y++)
            {
              for(int x = 0; x < wdth; x++)
              {
                int pixel = wBitmap.Pixels[((y * wdth) + x)];
                ei.SetPixel(x, y, (byte)((pixel >> 16) & 0xff), (byte)((pixel >> 8) & 0xff), (byte)(pixel & 0xff), (byte)((pixel >> 24) & 0xff));
              }
            }

            //Get the stream from the encoder and create byte array from it
            System.IO.Stream pngStream = ei.GetStream();
            
            printBuffer = new Byte[pngStream.Length];            
            pngStream.Read(printBuffer, 0, printBuffer.Length);

            switch (fsd.FilterIndex)
            {
              case 1:
                HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(new Uri(Application.Current.Host.Source.ToString().Substring(0, Application.Current.Host.Source.ToString().LastIndexOf("/")) + "/Png2Pdf.ashx"));
                hwr.Method = "POST";

                printStream = fsd.OpenFile();
                printSyncContext = System.Threading.SynchronizationContext.Current;
                hwr.BeginGetRequestStream(new AsyncCallback(PrintStart), hwr);

                break;
              case 2:
                //Save the PNG to local disk
                System.IO.Stream fs = fsd.OpenFile();
                fs.Write(printBuffer, 0, printBuffer.Length);
                fs.Close();
                MessageBox.Show("You PNG has been created.", "Export Complete", MessageBoxButton.OK);
                break;
            }
            
          }

        }

        private void PrintStart(IAsyncResult asynchronousResult)
        {
          HttpWebRequest hwr = (HttpWebRequest)asynchronousResult.AsyncState;
          System.IO.Stream stream = (System.IO.Stream)hwr.EndGetRequestStream(asynchronousResult);

          stream.Write(printBuffer, 0, printBuffer.Length);
          stream.Close();

          hwr.BeginGetResponse(new AsyncCallback(PrintGetResponse), hwr);
        }

        private void PrintGetResponse(IAsyncResult asynchronousResult)
        {
          HttpWebRequest hwr = (HttpWebRequest)asynchronousResult.AsyncState;
          WebResponse resp = hwr.EndGetResponse(asynchronousResult);
          System.IO.Stream respStream = resp.GetResponseStream();
          Byte[] respBytes = new Byte[respStream.Length];

          respStream.Read(respBytes, 0, respBytes.Length);

          printSyncContext.Post(PrintMergeThreads, new HttpWebRequestData(hwr, respBytes));
        }

        private void PrintMergeThreads(object state)
        {
          HttpWebRequestData hwrd = (HttpWebRequestData)state;

          printStream.Write(hwrd.Data, 0, hwrd.Data.Length);
          printStream.Close();
          printStream = null;
          printSyncContext = null;

          MessageBox.Show("Your PDF has been created.", "Export Complete", MessageBoxButton.OK);
        }
    
    }

}
